package sample.controller;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jfxtras.styles.jmetro.JMetro;
import jfxtras.styles.jmetro.Style;
import sample.context.Context;
import sample.pojo.User;
import sample.util.NetUtil;
import sample.context.StageManager;
import sample.context.ContextValues;
import java.io.IOException;

public class LoginController {

    @FXML
    private TextField usernameField;

    @FXML
    private Button loginbtn;

    @FXML
    private PasswordField passwordField;

    @FXML
    private Label state;

    @FXML
    private ComboBox<String> IPList;

    private boolean isPass = false;

    @FXML
    public void initialize() {
        if (NetUtil.isHostConnectable(ContextValues.port)) {
            // 窗口跳转
            state.setText(ContextValues.port + "端口检查通过");
            if (NetUtil.getHostIp()) {
                state.setText("IP地址: " + ContextValues.hostIp);
                isPass = true;
            }
            // IP选择框监听
            IPSelectListener();
        } else {
            state.setText("端口被占用,无法启动...");
            loginbtn.setDisable(true);
        }
    }

    @FXML
    void loginChatROOM(ActionEvent event) {
        String username = usernameField.getText();
        String password = passwordField.getText();

        // 用户登录验证
        if (!UserCheck(username.trim(), password.trim()) || !isPass) return;
        System.out.println("===>用户登录成功: " + username + " " + password);

        // 跳转界面
        ViewJump();

    }

    @FXML
    void registerChatROOM(ActionEvent event) {
        String username = usernameField.getText();
        String password = passwordField.getText();

        // 用户登录验证
        if (username.trim().isEmpty() || password.trim().isEmpty()){
            state.setText("用户名密码不能为空");
            return;
        }

        // 重写用户名密码
        ContextValues.adminUserName = username.trim();
        ContextValues.adminPassword = password.trim();

        state.setText("注册成功");
    }

    @FXML
    void cleanText(ActionEvent event) {
        usernameField.clear();
        passwordField.clear();
    }

    // 用户验证
    boolean UserCheck(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            state.setText("用户名密码不能为空");
            return false;
        }
        if (!username.equals(ContextValues.adminUserName) || !password.equals(ContextValues.adminPassword)) {
            state.setText("用户名和密码不正确");
            return false;
        }
        return true;
    }

    // 界面跳转
    void ViewJump() {
        // 网络验证
        Stage stage = new Stage();
        Parent root = null;
        try {
            root = FXMLLoader.load(Thread.currentThread().getContextClassLoader().getResource("MainView.fxml"));
            stage.setTitle("ChatROOM");
            Scene scene = new Scene(root);
            JMetro jMetro = new JMetro(Style.LIGHT);
            jMetro.setScene(scene);
            stage.setScene(scene);
            stage.show();

            // 监听窗口关闭
            stage.setOnCloseRequest(new EventHandler<javafx.stage.WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    System.exit(0);
                }
            });

            // 添加自己用户
            User adminUser = new User("本机",ContextValues.hostIp);
            adminUser.saveChattingRecord("========== 本 机 ==========");
            Context.addUser(adminUser);

            // 将第一个窗口隐藏
            StageManager.STAGE.get("LoginView").hide();
            //将第二个窗口保存到map中
            StageManager.STAGE.put("MainView", stage);
            //将本窗口保存到map中
            StageManager.CONTROLLER.put("loginControl", this);

        } catch (IOException e) {
            e.printStackTrace();
            state.setText("页面跳转出错");
        }
    }

    public void IPSelectListener(){
        IPList.setItems(FXCollections.observableArrayList(NetUtil.getLocalIPList()));
        IPList.getSelectionModel().select(0);
        //设置连接选择框被选中
        IPList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>()
        {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue)
            {
                ContextValues.hostIp = newValue;
                state.setText("IP地址: " + ContextValues.hostIp);
            }
        });
    }
}
